import { _decorator, Color, Component, Label, Node, Sprite, Vec2 } from 'cc';
import { Global } from './Global';
import { PropsAction } from './PropsAction';
import { Clips } from './Enums';
import { AudioManger } from './AudioManger';
import { CatAction } from './CatAction';
import { DataModel } from './DataModel';
import { AdManger } from './ad/AdManger';
import { ColorDate } from './ColorDate';

const { ccclass, property } = _decorator;

@ccclass('Props4Action')
export class Props4Action extends Component {

    @property(Node)
    target: Node = null!;

    @property(Sprite)
    cat_img: Sprite = null!;

    private color_arr: ColorDate[] = [];
    private color_arr_index: number = 0;

    private cat_action: CatAction | null = null;

    @property({ type: Label })
    coins_label: Label = null!;

    private dt: number = 0;
    private times: number = 0;

    start() {
        this.coins_label.string = Global.get_need_coins().toString();

        // 克隆颜色数组，避免引用问题
        this.color_arr = DataModel.base_color_arr.map(c => c.clone());
    }

    update(deltaTime: number) {
        if (!this.node.active) return;

        if (this.times === 0) {
            this.times++;
            this.play_tween();
        } else {
            this.dt += deltaTime;
            if (this.dt >= 1) {
                this.dt = 0;
                this.play_tween();
            }
        }
    }

    private play_tween() {
        this.color_arr_index = (this.color_arr_index + 1) % this.color_arr.length;
        const c = this.color_arr[this.color_arr_index];
        this.cat_img.color = new Color(c.r, c.g, c.b, 255);
    }

    show_box(cat_action: CatAction) {
        this.cat_action = cat_action;
    }

    open_box_coins() {
        AudioManger.instance.playSound(Clips.btn_1);

        if (Global.cur_coins < Global.get_need_coins()) {
            Global.tips_action.show_for_bs("扳手数量不够");
            return;
        }

        Global.use_coins(Global.get_need_coins());

        if (this.cat_action) {
            this.cat_action.set_lock_unlock(false);
            this.cat_action.into_scence(new Vec2(0, 400));
        }

        Global.coins_action.refresh_coins();

        this.node.parent.getComponent(PropsAction)?.close();
    }

    open_box_video() {
        AudioManger.instance.playSound(Clips.btn_1);

        if (!this.cat_action) return;

        AdManger.show_video((data) => {
            if (data === 1) {
                console.log("open_box_video 获取奖励成功");
                this.node.parent.getComponent(PropsAction)?.close();
                this.cat_action!.set_lock_unlock(false);
                this.cat_action!.into_scence(new Vec2(0, 400));
            } else {
                Global.tips_action.show("获取奖励失败");
                // 如果有退款逻辑，取消注释这里
                // Global.return_used_cur_level_props_(4);
            }
        });
    }

    open() {
        this.coins_label.string = Global.get_need_coins().toString();
    }
}
